<?php
/**
 * (logic)
 */
namespace App\Logic\MonthlyReport;

use App\Models\MonthlyReport\Cost\LogisticsBalance;
use App\Models\MonthlyReport\Cost\LogisticsBasics;
use App\Models\MonthlyReport\Cost\LSaleRecord;
use App\Models\MonthlyReport\Cost\OrderBasics;
use Illuminate\Support\Facades\DB;
class CheckLogisticsBasics
{
    public static function exe($func,$date)
    {
        if('null' == $date){
            $time = strtotime('midnight first day of -1 month');
        }else{
            $time = strtotime($date);
        }
        try{
            DB::beginTransaction();
            self::{$func}($time);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 3.更新所有为0的物流成本
     * @param $time
     */
    private static function _upLogisticsForAll($time){
        $date = date('Y-m-01',$time);
        $ls = LogisticsBasics::query()
            ->where('b_date',$date)
            ->where('price',0)
            ->get();
        foreach ($ls as $line){
            $mix = LogisticsBasics::query()
                ->where('area_id',$line->area_id)
                ->where('psku_id',$line->psku_id)
                ->where('price','<>',0)
                ->where('b_date','<',$date)
                ->orderBy('b_date','DESC')
                ->first();
            if(!$mix)continue;
            $line->price = $mix->price;
            $line->save();
        }
    }

    /**
     * 2.更新UK为0的物流成本
     * @param $time
     */
    private static function _upLogisticsForUK($time){
        $date = date('Y-m-01',$time);
        $maxDate = date('Y-m-t 23:59:59',$time);
        $ls = LogisticsBasics::query()
            ->where('b_date',$date)
            ->where('area_id',3)
            ->where('price',0)
            ->get();
        foreach ($ls as $line){
            $mix = LogisticsBalance::query()
                ->where('area_id',4)//取欧洲数据
                ->where('psku_id',$line->psku_id)
                ->where('b_balance_sale','>',0)
                ->where('delivered_at','<=',$maxDate)
                ->orderBy('delivered_at','ASC')
                ->get();
            if($mix->isEmpty()){//不足取倒序
                $needDis = $line->quantity;
                $fBalanceEmpty = LogisticsBalance::query()
                    ->where('area_id',4)
                    ->where('psku_id',$line->psku_id)
                    ->where('delivered_at','<=',$maxDate)
                    ->orderBy('delivered_at','DESC')
                    ->first();
                if($fBalanceEmpty){
                    $sum = $fBalanceEmpty->b_price * $needDis;
                    LSaleRecord::query()->create([
                        'area_id' => 4,
                        'psku_id' => $line->psku_id,
                        'delivery_no' => $fBalanceEmpty->delivery_no,
                        'b_num' => $needDis,
                        'b_balance' => $fBalanceEmpty->b_balance_sale,
                        'is_previous_balance' => 1,//是否是往期结存：1.是
                    ]);
                }else{
                    $sum = 0;
                }
            }else{
                $needDis = $line->quantity;
                $sum = 0;
                foreach($mix as $_mix){
                    if($needDis == 0)break;
                    $min = min($needDis,$_mix->b_balance_sale);
                    $needDis -= $min;
                    $_mix->b_balance_sale -= $min;
                    $_mix->save();
                    LSaleRecord::query()->create([
                        'area_id' => $line->area_id,
                        'psku_id' => $line->psku_id,
                        'delivery_no' => $_mix->delivery_no,
                        'b_num' => $min,
                        'b_balance' => $_mix->b_balance_sale,
                    ]);
                    $sum += $min * ($_mix->b_price ?? 0);
                }
                if($needDis > 0){//不足取倒序
                    $fBalance = LogisticsBalance::query()
                        ->where('area_id',4)
                        ->where('psku_id',$line->psku_id)
                        ->where('delivered_at','<=',$maxDate)
                        ->orderBy('delivered_at','DESC')
                        ->first();
                    if($fBalance){
                        $sum += $fBalance->b_price * $needDis;
                        LSaleRecord::query()->create([
                            'area_id' => 4,
                            'psku_id' => $line->psku_id,
                            'delivery_no' => $fBalance->delivery_no,
                            'b_num' => $needDis,
                            'b_balance' => $fBalance->b_balance_sale,
                            'is_previous_balance' => 1,//是否是往期结存：1.是
                        ]);
                    }
                }
            }
            $line->price = round($sum / $line->quantity,3);
            $line->save();
        }
    }

    /**
     * 1.订单sku价格
     * @param $time
     */
    private static function _mixCSkuPriceBasics($time){
        $date = date('Y-m-01',$time);
        $maxDate = date('Y-m-t 23:59:59',$time);
        $lines = OrderBasics::query()
            ->select(DB::raw('area_id,psku_id,sum(quantity) as quantity'))
            ->where('b_date',$date)
            ->where('psku_id','<>',0)
            ->groupBy(['area_id','psku_id'])
            ->get();
        $i = 0;
        $num = 200;
        while(true){
            if($lines->isEmpty())break;
            $_lines = $lines->splice($i,$num);
            foreach ($_lines as $line){
                if($line->quantity == 0)continue;
                $mix = LogisticsBalance::query()
                    ->where('area_id',$line->area_id)
                    ->where('psku_id',$line->psku_id)
                    ->where('b_balance_sale','>',0)
                    ->where('delivered_at','<=',$maxDate)
                    ->orderBy('delivered_at','ASC')
                    ->get();
                if($mix->isEmpty()){//未匹配到订单对应的SKU时取倒序
                    $needDis = $line->quantity;
                    $fBalanceEmpty = LogisticsBalance::query()
                        ->where('area_id',$line->area_id)
                        ->where('psku_id',$line->psku_id)
                        ->where('delivered_at','<=',$maxDate)
                        ->orderBy('delivered_at','DESC')
                        ->first();
                    if($fBalanceEmpty){
                        $sum = $fBalanceEmpty->b_price * $needDis;
                        LSaleRecord::query()->create([
                            'area_id' => $line->area_id,
                            'psku_id' => $line->psku_id,
                            'delivery_no' => $fBalanceEmpty->delivery_no,
                            'b_num' => $needDis,
                            'b_balance' => $fBalanceEmpty->b_balance_sale,
                            'is_previous_balance' => 1,//是否是往期结存：1.是
                        ]);
                    }else{
                        $sum = 0;
                    }
                }else{
                    $needDis = $line->quantity;
                    $sum = 0;
                    foreach($mix as $_mix){
                        if($needDis == 0)break;
                        $min = min($needDis,$_mix->b_balance_sale);
                        $needDis -= $min;
                        $_mix->b_balance_sale -= $min;
                        $_mix->save();
                        LSaleRecord::query()->create([
                            'area_id' => $line->area_id,
                            'psku_id' => $line->psku_id,
                            'delivery_no' => $_mix->delivery_no,
                            'b_num' => $min,
                            'b_balance' => $_mix->b_balance_sale,
                        ]);
                        $sum += $min * ($_mix->b_price ?? 0);
                    }
                    if($needDis > 0){//差额取倒序
                        $fBalance = LogisticsBalance::query()
                            ->where('area_id',$line->area_id)
                            ->where('psku_id',$line->psku_id)
                            ->where('delivered_at','<=',$maxDate)
                            ->orderBy('delivered_at','DESC')
                            ->first();
                        if($fBalance){
                            $sum += $fBalance->b_price * $needDis;
                            LSaleRecord::query()->create([
                                'area_id' => $line->area_id,
                                'psku_id' => $line->psku_id,
                                'delivery_no' => $fBalance->delivery_no,
                                'b_num' => $needDis,
                                'b_balance' => $fBalance->b_balance_sale,
                                'is_previous_balance' => 1,//是否是往期结存：1.是
                            ]);
                        }
                    }
                }
                $price = round($sum / $line->quantity,3);
                LogisticsBasics::query()->updateOrCreate(
                    [
                        'b_date' => $date,
                        'area_id' => $line->area_id,
                        'psku_id' => $line->psku_id,
                    ],
                    [
                        'quantity' => $line->quantity,
                        'price' => $price
                    ]);
            }
        }
    }
}
